//解析图片json数据
/*
 <div class="photo-frame">
      <div class="img"></div>
      <div class="row">
          <a>复制地址:</a>
          <input type="text" class="url">
      </div>
      <div class="s-row">
          <input class="checkbox" type="checkbox"/>
          <span>这里是标题美女图片一</span>
      </div>
      <div class="s-row">
          <a class="icon del-icon">删除</a>
          <a class="icon upload-icon">重传</a>
          <a class="icon download-icon">下载</a>
      </div>
  </div>
 */
//全部事件监听
$('.allCheckbox').click(function(){
	if($(this).attr('checked'))
		$('#photo-content .photo-frame .s-row .checkbox').attr('checked',true);
	else
		$('#photo-content .photo-frame .s-row .checkbox').attr('checked',false);
});

$('.control .reloadbtn').click(function(){
	window.location.reload();
});

$('.control .delbtn').click(function(){
	if(confirm('你确认是否删除所选的图片？')){
		//统计删除的数量
		var delConut = 0;
		$('#photo-content .photo-frame .s-row .checkbox').each(function(){
			if($(this).attr('checked')){
				delConut++;
				var photoId = $(this).parent().parent().attr('photoid');

			    $.ajax({ 
					type : "post", 
					url : "/manage/album/album/delPhotoByPhotoId", 
					data : {'photoId' : photoId}, 
					async : false, 
					success : function(data){ 
						if (data.error) {
							alert(data.error);
						}
					} 
			    });  
			}
		});
		//alert(123);
		if(delConut>0){
			window.location.reload();
		}
	}
});

function uploadImg(fileElementId,pictitle,imgFrame){
	$.ajaxFileUpload(
	{
	    url:'/manage/album/album/uploadAlbum',            //需要链接到服务器地址
	    secureuri:false,
	    fileElementId:fileElementId,                        //文件选择框的id属性
	    dataType: 'json',                                     //服务器返回的格式，可以是json
	    data: {//加入的文本参数  
            "folder": "userAlbum",  
            "albumId": $('input[name="albumId"]').val(),
            "pictitle":pictitle
        },  
	    success: function (data, status)            //相当于java中try语句块的用法
	    {   
	    	imgFrame.empty();
	    	var img = $('<img/>').attr('src',data.photoUrl);
	    	calculatePhoto(data,img,200,200);
	    	img.appendTo(imgFrame);
	    },
	    error: function (data, status, e)            //相当于java中catch语句块的用法
	    {
	    	alert('网络异常，请重试！');
	    }
	});
}


$('.control .btn').hover(function(){
	$(this).addClass('btn-mouseover');
},function(){
	$(this).removeClass('btn-mouseover');
});

//其他样式效果补丁
$('.control .page .page-num').click(function(){
	$(this).find('.options').show();
});

//增加一个图片按钮事件
$('.control .addPhoto').click(function(){
	//添加一个图片
	var addPhoto = $.ui_dialog_create();
	addPhoto._create({
		shelter:true,					//是否遮挡
		title:'上传图片',				//标题
		isDrag:false,
		requestUrl:'',					//请求地址
		width:530,						//弹出框宽度
		height:'auto',					//弹出框高度
		uiDialogExClass:'ui-dialog',	//扩展名
		bindId:'addAlbumDiv',			//绑定的ID
		noClone:true,				//非克隆DIV
		postUrl:'',						//post请求地址
		callback: {
			closeDialog:function(contentDiv){
				contentDiv.find('.img').empty();
				contentDiv.find('input[name="albumTitle"]').val('');
				contentDiv.find('input[name="imageToUpload"]').val('');
			},
			//开启后执行
			openDialog:function(contentDiv){
				//按时间默认生成一个标题
				contentDiv.find('input[name="albumTitle"]').val(new Date().getTime());
				contentDiv.find('.upload').click(function(){
					if(contentDiv.find('input[name="imageToUpload"]').val())
						uploadImg('imageToUpload',contentDiv.find('input[name="albumTitle"]').val(),contentDiv.find('.img'));
					else
						alert('请选择图片再上传！');
				});
			},
			//确认事件 等于1就继续执行并且关闭
			confirmDialog:function(contentDiv){							
				var uploadUrl = contentDiv.find('#imageToUpload').val();
				if(!uploadUrl){
					return 0;
				}else{
					window.location.reload();
					return 1;	
				}
				
			}
		}
	});
	addPhoto.openDialog();
});

$(window.document.body).bind('click.pageJump',function(e){
	var target = $(e.target);
	var result = false;
	for(var i=0;i<3;i++){
		if(target.hasClass('page-num')){
			result = true;
			break;
		}else{
			target = target.parent();	
		}
	}
	
	if(!result)
		$('.control .page .page-num .options').hide();
});

//解析图片函数
function analyticalPhotoJson(photoJson){
	$('.allCheckbox').attr('checked',false);
	$('#photo-content').empty();
	var bool = new Array();
	if(photoJson && photoJson.length>0){
		for(var i=0;i<photoJson.length;i++){
			var photoFrame = $('<div></div>').attr({
				'photoCreateDate':photoJson[i].photoCreateDate,
				'photoId':photoJson[i].photoId
			}).addClass('photo-frame').appendTo('#photo-content');
			var imgDiv = $('<div></div>').addClass('img').appendTo(photoFrame);
			bool[i] = true;
            var img = $('<img/>').attr({
                src : photoJson[i].photoUrl
            }).load((function(i){
                return function(){
                    if(bool[i])
                        calculatePhoto(photoJson[i], $(this), 200, 200);
                };
            })(i)).error((function(i) {
                return function(){
                    bool[i] = false;
                    this.src=MANAGEERRORIMGSRC;
                    this.style.marginLeft = '65px';
                    this.style.marginTop = '65px';
                };
            })(i));
			img.appendTo(imgDiv);
			var row = $('<div></div>').addClass('row').appendTo(photoFrame);
			var rowA = $('<a></a>').text('复制地址:').appendTo(row);
			var rowInt = $('<input type="text"/>').addClass('url').val(photoJson[i].photoUrl).appendTo(row);
			var sRow1 = $('<div></div>').addClass('s-row').appendTo(photoFrame);
			var sRow1Checkbox = $('<input type="checkbox"/>').addClass('checkbox').click(function(){
				var checkState = false;
				$('#photo-content .photo-frame .s-row .checkbox').each(function(){
					if($(this).attr('checked'))
						checkState = true;
				});
				$('.allCheckbox').attr('checked',checkState);
			}).appendTo(sRow1);
			var sRow1Span = $('<span></span>').text(photoJson[i].photoTitle?photoJson[i].photoTitle:'暂无标题').appendTo(sRow1);
			var sRow2 = $('<div></div>').addClass('s-row').appendTo(photoFrame);
			var delIcon = $('<a></a>').addClass('icon').text('删除').addClass('del-icon').attr('photoId',photoJson[i].photoId).click(function(){
				if(confirm('确认是否删除该图片?')){
					$.post('/manage/album/album/delPhotoByPhotoId',{
						photoId : $(this).attr('photoId')
					},function(data){
						if (data.error) {
							alert(data.error);
						}else
							window.location.reload();
					});
				}
			}).appendTo(sRow2);
			//var uploadIcon = $('<a></a>').addClass('icon').text('重传').addClass('upload-icon').appendTo(sRow2);
			var downloadIcon = $('<a></a>').attr('href',globalUrl+photoJson[i].photoUrl).addClass('icon').text('下载').addClass('download-icon').appendTo(sRow2);
		}
		$('#photo-content').append('<div class="auto-height"></div>');
	}
}
//解析图片
analyticalPhotoJson(photosJson);
//解析分页数据
analyticalPageJson(pageInfoJson);

//计算图片位置
function calculatePhoto(photo,img,frameWidth,frameHeight){
	
	//如果不需要缩小
	if(photo.photoWidth<=frameWidth && photo.photoHeight<=frameHeight){
		//计算左右边距
		img.css({
			marginTop:(frameHeight-photo.photoHeight)/2,
			marginLeft:(frameWidth-photo.photoWidth)/2
		});
	}
	//如果需要缩小
	else{
		photo.photoWidth = parseInt(photo.photoWidth);
		photo.photoHeight = parseInt(photo.photoHeight);
		//按长的一边的比例进行缩小
		//如果宽比高长,宽就变成边框宽
		//alert('photo.photoWidth:'+photo.photoWidth+'\n'+'photo.photoHeight:'+photo.photoHeight+'\n');
		if(photo.photoWidth>photo.photoHeight){
			img.css({
				width:frameWidth,
				height:frameWidth/photo.photoWidth*photo.photoHeight,
				marginTop:Math.floor((frameHeight-frameWidth/photo.photoWidth*photo.photoHeight)/2)
			});
		}else if(photo.photoWidth<photo.photoHeight){
			img.css({
				height:frameHeight,
				width:frameHeight/photo.photoHeight*photo.photoWidth,
				marginLeft:Math.floor((frameWidth-frameHeight/photo.photoHeight*photo.photoWidth)/2)
			});
		}else{
			img.css({
				height:frameHeight,
				width:frameHeight
			});
		}
	}
}

//分页参数处理
function dataDealPageInfo(pageInfo){
	if(pageInfo){
		//当前页不能大于总页数
		if(pageInfo.currentPage>pageInfo.countPage)
			pageInfo.currentPage = pageInfo.countPage;
		//当前页不能小于1
		if(pageInfo.currentPage<1)
			pageInfo.currentPage = 1;
			
		//是否有上一页
		if(pageInfo.currentPage<=1)
			pageInfo.isPrePage = false;
		else
			pageInfo.isPrePage = true;
			
		//是否有下一页
		if(pageInfo.currentPage>=pageInfo.countPage)
			pageInfo.isNextPage = false;
		else
			pageInfo.isNextPage = true;
	}
	return pageInfo;
}

$('.control .ins-go').click(function(){
	var conditions = $.merge($('form[name="parameters"]').serializeArray(),$(this).parent().serializeArray());
	$.post('/manage/album/album/albumPage',conditions,function(data){
		eval('var datao = '+data+';');
	    analyticalPhotoJson(datao.photosData);
	    analyticalPageJson(datao.pageInfo);
	});
});

//解析分页数据
function analyticalPageJson(pageInfo){
	pageInfo = dataDealPageInfo(pageInfo);
	var pageNumNode = $('.control .page .page-num');
	var pagePre = $('.control .page .pre');
	var pageNext = $('.control .page .next');
	var pageBtn = $('.control .page .page-btn');
	//确定当前页数和总页数当前显示
	pageNumNode.find('font').text(pageInfo.currentPage+'/'+pageInfo.countPage);
	//确定选项卡
	var options = pageNumNode.find('.options').empty();
	for(var i=0;i<pageInfo.countPage;i++){
		var option = $('<div></div>').attr('value',i+1).addClass('option').text((i+1)+'/'+pageInfo.countPage).click(function(){
			var currentPage = $(this).attr('value');
			$(this).parent().find('.option').removeClass('current');	
			$(this).addClass('current');
			$(this).parent().hide();
			$(this).parent().parent().find('font').text($(this).text());
		    
			//修改参数条件数据集合
			$('input[name="currentPage"]').val(currentPage);
			$.post('/manage/album/album/albumPage',$('form[name="parameters"]').serializeArray(),function(data){
			    eval('var datao = '+data+';');
			    analyticalPhotoJson(datao.photosData);
			    analyticalPageJson(datao.pageInfo);
			});
			return false;
		}).hover(function(){
			$(this).addClass('mouseover');
		},function(){
			$(this).removeClass('mouseover');
		}).appendTo(options);
	}

	pageBtn.hover(function(){
	    if($(this).hasClass('pre')){
	    	if(!$(this).find('.pre-ico').hasClass('pre-ico-disable'))
	    		  $(this).addClass('page-btn-mouseover');
		}else if($(this).hasClass('next')){
			if(!$(this).find('.next-ico').hasClass('next-ico-disable'))
	    		  $(this).addClass('page-btn-mouseover');
		}						
	},function(){
		$(this).removeClass('page-btn-mouseover');
	});
    
	pagePre.find('.pre-ico').unbind('click');
	//确定上一页和下一页  
	if(pageInfo.isPrePage)
		pagePre.find('.pre-ico').unbind('click').click(function(){
			//当前页面数减1
			var currentPage = parseInt($('input[name="currentPage"]').val());
			if(currentPage>1)
				currentPage--;
			//修改参数条件数据集合
			$('input[name="currentPage"]').val(currentPage);
			$.post('/manage/album/album/albumPage',$('form[name="parameters"]').serializeArray(),function(data){
			    eval('var datao = '+data+';');
			    analyticalPhotoJson(datao.photosData);
			    analyticalPageJson(datao.pageInfo);
			});
			
		}).removeClass('pre-ico-disable');
	else
		pagePre.find('.pre-ico').addClass('pre-ico-disable');
	
	pageNext.find('.next-ico').unbind('click');
	if(pageInfo.isNextPage)
		pageNext.find('.next-ico').unbind('click').click(function(){
			//当前页面数加1
			var currentPage = parseInt($('input[name="currentPage"]').val());
			if(currentPage<pageInfo.countPage)
				currentPage++;
			//修改参数条件数据集合
			$('input[name="currentPage"]').val(currentPage);
			$.post('/manage/album/album/albumPage',$('form[name="parameters"]').serializeArray(),function(data){
			    eval('var datao = '+data+';');
			    analyticalPhotoJson(datao.photosData);
			    analyticalPageJson(datao.pageInfo);
			});
		}).removeClass('next-ico-disable');
	else
		pageNext.find('.next-ico').addClass('next-ico-disable');
}
